<?php

session_start();
// Connect to the DB.
$_SESSION["errmsg"] = '';
$_SESSION["successmsg"] = '';

require_once '../include/config.lib.php';
require_once '../include/database.lib.php';

$timelimit = 60; //1 minute
$additionlimit = 2;

function buildRedirectPath($redirectTo) {
	return "<HTML><META http-equiv=\"refresh\" content=\"0; url='".$redirectTo."'\"></HTML>";
	/*return 'error:'.$_SESSION["errmsg"].'<br/>';
	return 'success:'.$_SESSION["successmsg"].'<br/>';*/
}

function limitAdditions($timelimit, $additionlimit){
	
	if(isset($_SESSION['firstaddition'])){
		$_SESSION['numadditions']++;		
		
		if((time() - $_SESSION['firstaddition']) > $timelimit){ //reset
			$_SESSION['firstaddition'] = time();
			$_SESSION['numadditions'] = 1;						
		}
		else{
			if($_SESSION['numadditions'] > $additionlimit)
				return true; //avoid this addition (limit it)
		}
	}
	else{
		$_SESSION['firstaddition'] = time();
		$_SESSION['numadditions'] = 1;
	}
	return false; // do not limit, it is ok
}

if(isset($_POST['submitCheck'])) {	//Test if the form has been submitted
	
	ConnectToDB();
	$bibidOfAlreadyExists = null;
	
	//Get user ID to anchor the form when user clicks on the Claim Paper button
	$selectid = DBExecute("SELECT id FROM person WHERE username = ?", $_SESSION["accountNo"]);
	$id = $selectid->fetchAssocRow();//find the person's id to redirect to the person's own page
	$url = "../person_view.php?id=".$id["ID"]."#maintabs-3";
	$personid = $id["ID"];				
	
	
	//perform form validation
	$errorTitle = false; $errorTitleLength = false; $errorAuthors = false; $errorAuthorsLength = false; 
	$errorDOI = false; $errorISBN = false; $errorJournal = false; $errorVolume = false; $errorPages = false; $errorYear = false;
	
	// Get data from POST string. Trim spaces
	$title = trim($_REQUEST['title']);
	$authors = trim($_REQUEST['authors']);
	$authorNames = explode(';', $authors);			//separate authors via delimiting semicolon
	for($i = 0; $i< count($authorNames); $i++){	//trim spaces from names and change to lowercase
		$authorNames[$i] = trim($authorNames[$i]);
		$authorNames[$i] = strtolower($authorNames[$i]);
	}
	$abstract = isset($_REQUEST['abstract']) ? trim($_REQUEST['abstract']) : null;
	$doi = isset($_REQUEST['doi']) ? trim($_REQUEST['doi']) : null;
		if( $doi == '' ){$doi = null;}
	$isbn = isset($_REQUEST['isbn']) ? trim($_REQUEST['isbn'])  : null;
		if( $isbn == '' ){$isbn = null;}
	$journal = isset($_REQUEST['journal']) ? trim($_REQUEST['journal']) : null;
	$volume = isset($_REQUEST['volume']) ? trim($_REQUEST['volume']) : null;
	$pages = isset($_REQUEST['pages']) ? trim($_REQUEST['pages']) : null;
	$year = isset($_REQUEST['year']) ? trim($_REQUEST['year']) : null;
	
	//check that mandatory fields are filled in
	if (strlen($title)<4){
		$errorTitleLength = true;	//min field lanegh of 4
	}
	else $errorTitleLength = false;
	
	if (strlen($authors)<3){
		$errorAuthorsLength = true; //min field length of 3
	}
	else $errorAuthorsLength = false;
	
	//check format of fields
	if (!preg_match("/^[a-zA-Z0-9\,\;\.\s]*$/", $title)){
		$errorTitle = true;
	}
	else $errorTitle = false;
	
	if (!preg_match("/^[a-zA-Z0-9\,\;\.\s]*$/", $authors)){
		$errorAuthors = true;
	}
	else $errorAuthors = false;
	
	if (!preg_match("/^[0-9]*$/", $doi)){
		$errorDOI = true;
	}
	else $errorDOI = false;
	
	if (!preg_match("/^[0-9]*$/", $isbn)){ 
		$errorISBN = true;
	}
	else $errorISBN = false;
	
	if (!preg_match("/^[a-zA-Z0-9\;\s]*$/", $journal)){ 
		$errorJournal = true;
	}
	else $errorJournal = false;
	
	if (!preg_match("/^[0-9]*$/", $volume)){ 
		$errorVolume = true;
	}
	else $errorVolume = false;
	
	if (!preg_match("/^[0-9-]*$/", $pages)){ 
		$errorPages = true;
	}
	else $errorPages = false;
	
	if (!preg_match("/^[0-9-]*$/", $year)){ 
		$errorYear = true;										
	}
	else $errorYear = false;	
	
		//check if resource is already in DB								
	$alreadyExists = false;
	$duplicateTitle = false;
	$duplicateDOI = false;
	$duplicateISBN = false;
	//check for duplicate titles in the DB
	$check1 = DBExecute('SELECT id FROM bibtex b WHERE lower(b.title) = ?', array(strtolower($title)));
	if( $rowtmp = $check1->fetchAssocRow() ){
		$alreadyExists = true;
		$duplicateTitle = true;
		$bibidOfAlreadyExists = $rowtmp['ID'];
	}
	
	
	
	//check for duplicate DOIs in the DB if one was entered
	if( $doi != null && $doi != ''){
		$check2 = DBExecute('SELECT id FROM bibtex b WHERE b.doi = ?', array($doi));
		if( $rowtmp = $check2->fetchAssocRow() ){
			$alreadyExists = true;
			$duplicateDOI = true;
			$bibidOfAlreadyExists = $rowtmp['ID'];
		}
	}									

	//check for duplicate ISBNs in the DB if one was entered
	if( $isbn != null && $isbn != ''){
		$check3 = DBExecute('SELECT id FROM bibtex b WHERE b.isbn = ?', array($isbn));
		if( $rowtmp = $check3->fetchAssocRow() ){
			$alreadyExists = true;
			$duplicateISBN = true;
			$bibidOfAlreadyExists = $rowtmp['ID'];
		}
	}		

	//check if there was an input error
	if($errorTitle==true || $errorTitleLength==true || $errorAuthors==true || $errorAuthorsLength==true || $errorDOI==true || $errorISBN==true || $errorJournal==true || $errorVolume==true || $errorPages==true || $errorYear==true){
		//output error message for invalid field entries
		$_SESSION["errmsg"] = "Invalid input in the following fields: " . "<br/>";		
			if ($errorTitle || $errorTitleLength) $_SESSION["errmsg"] .= "- Title ". "<br/>";
			if ($errorAuthors || $errorAuthorsLength) $_SESSION["errmsg"] .= "- Author(s) ". "<br/>";
			if ($errorDOI) $_SESSION["errmsg"] .= "- DOI  ". "<br/>";		
			if ($errorISBN) $_SESSION["errmsg"] .= "- ISBN  ". "<br/>";
			if ($errorJournal) $_SESSION["errmsg"] .= "- Journal  ". "<br/>";	
			if ($errorVolume) $_SESSION["errmsg"] .= "- Volume  ". "<br/>";
			if ($errorPages) $_SESSION["errmsg"] .= "- Page(s)  ". "<br/>";
			if ($errorYear) $_SESSION["errmsg"] .= "- Year of Publication ". "<br/>";		
		$_SESSION["errmsg"] .= "Please correct these fields and resubmit" . "<br/>";
		
		echo buildRedirectPath($url);
	}
	
	/*else if($alreadyExists == true){ //If the publication already exists, dont add it, nd inform the user
		$_SESSION["errmsg"] .= 'Duplicate fields: '. '<br>';
		if($duplicateTitle == true){ $_SESSION["errmsg"] .=  'Title' . '<br>';}
		if($duplicateDOI == true){ $_SESSION["errmsg"] .= 'DOI' . '<br>';}
		if($duplicateISBN == true){ $_SESSION["errmsg"] .= 'ISBN' . '<br>';}
		//$_SESSION["errmsg"] .= 'This resource has already been added under the title: ' . $title. "<br>";
		//echo buildRedirectPath($url);
	}*/
	
	else{	//add the publication to the databse
		$uploadError = false;
		$target_path = "../upload/". $personId;

			//check for security
			if(limitAdditions($timelimit,$additionlimit) == true){
				$_SESSION["errmsg"] .= "Sorry, for security reasons we have put a time limit on submissions. You can only add ".$additionlimit." publications per ".$timelimit." seconds. <br/>";
				echo buildRedirectPath($url);	
				$uploadError = true;			
			}
		
			else if ($_FILES["file"]["name"] != null){	//if there is a file, upload it
				$extension = substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], '.') + 1);
				$randNumber = rand(100000, 999999);	//rand gives a random number between a given min and max
				
				$target_path = $target_path . "-" .  $randNumber . "." . $extension;

				//only upload the file if its extension is pdf, img, jpg, or png
				if (($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || 
				    ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "application/pdf") || 
				    ($_FILES["file"]["type"] == "application/img") || ($_FILES["file"]["type"] == "application/png")){
				
					if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_path)) {	//confirmation message
				    	$_SESSION["successmsg"] .= "The file ".  basename( $_FILES["file"]["name"]). " has been uploaded" . "<br>";
						$_SESSION["successmsg"] .= "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
					} 
					else{
			    		$_SESSION["errmsg"] .= "There was an error uploading the file, please try again!" . "<br>";
			    		$uploadError = true;
			    		echo buildRedirectPath($url);
					}
				}
				else{
					$_SESSION["errmsg"] .= "Invalid filetype. Please only upload pdf, img, jpg, or png files" . "<br>";
			    	$uploadError = true;
			    	echo buildRedirectPath($url);
				}
			}
		

		if($uploadError == false){ //if the paper is uploaded properly, or no file was uploaded, then add the information to the DB
			
			
			
			if($alreadyExists != true){ //if it doesn't exist, add it
				//add the new resource to the bibtex table
				$check = DBExecute("INSERT INTO bibtex (bibtex, title, doi, issn, isbn, abstract, uploadpath, authors) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", 
					array(null, $title, $doi, null, $isbn, $abstract, $target_path, $authors));
				$newEntry = DBExecute("select bibtex.id as id from bibtex where title = ?", array($title));	//retrieve the new bibtex id
				$newBibtexID = $newEntry->fetchAssocRow();
				
				//add the new resource to the resource table
				$bibtexid = $newBibtexID['ID'];
				$target_path = $target_path . $bibtexid;
				$check2 = DBExecute("INSERT INTO resource (url, bibtexid, documentdigest, documenttextdigest) VALUES(?, ?, ?, ?)", 
					array($target_path, $bibtexid, null, null));
					
				//find the resource which was just added (resourceid is found based on: personid and bibtexid, so it will actually consider bibtex which is what we want
				//$newEntry2 = DBExecute("select resource.id as id from resource where url = ?", array($target_path));	//retrieve the new resource id
				
			}
			else{
				$bibtexid = $bibidOfAlreadyExists;
				//find the resource which has this bib
				//$newEntry2 = DBExecute("select r.id as id from resource r, bibtex b where r.bibtexid = b.id and b.title = ?", array($title));	//retrieve the new bibtex id				
			}
			
			/*while($newResourceID = $newEntry2->fetchAssocRow()){
				//check if author exists for any of resources with that bib 
				$authorListerReq = DBExecute("select id from authoring where personid=? and resourceid=?", array($id,$newResourceID['ID']));
				if( $authorListerReq->fetchAssocRow()){
					$_SESSION["errmsg"] .= "You have already been added as the author of this resource <br/>";					
				}
				else{
					DBExecute("insert into authoring (personid,resourceid) values (?,?)",array($id,$newResourceID['ID']));
				}
			}*/
			
			$authorListerReq = DBExecute("select personid from authoringbib where personid=? and bibtexid=?", array($personid,$bibtexid));
			if( $authorListerReq->fetchAssocRow()){
				$_SESSION["errmsg"] .= "You have already been added as the author of this resource <br/>";					
			}
			else{
				DBExecute("INSERT INTO authoringbib (personid,bibtexid) VALUES (?,?)",array($personid,$bibtexid));				
			}		
			
			
			
			/*for($i = 0; $i< sizeof($authorNames); $i++){
				//check if author name is already in DB
				$authorCheck1 = DBExecute("SELECT COUNT(*) as matches FROM person p WHERE lower(p.name) = ? AND p.username IS null", array(strtolower($authorNames[$i])));
				$num = $authorCheck1->fetchAssocRow();
				
				$resourceIDs = DBExecute(' SELECT r.id AS resourceID FROM resource r
					WHERE r.bibtexid = ?', array($newBibtexID['ID'])); //resource ids from this paper
				
				if($num['MATCHES'] > 0){	//if the author already exists in the DB, so just add them to the autoring table
					//retrieve the ID of the author so we can add it to the authoring table
					$authorIDreq = DBExecute("SELECT id FROM person p WHERE lower(p.name) = ? AND p.username IS null", array(strtolower($authorNames[$i])));
					$authorID = $authorIDreq->fetchAssocRow();
			
					while ( $row = $resourceIDs->fetchAssocRow()) {	//add autoring entries for each resource associated with the paper
						$resourceID = $row['RESOURCEID'];
						$newAuthor = DBExecute("INSERT INTO authoring (personid,resourceid) VALUES (?, ?)", array($authorID['ID'], $resourceID));
					}
				}

				else{	//if the author doesnt yet exist in the DB, then add them to the Authoring table and Person table
					//insert the new person into the person table
					$newPerson = DBExecute("INSERT INTO person (name) VALUES (?)", array($authorNames[$i]));
					
					//retrieve the ID of the new person
					$authorIDreq = DBExecute("SELECT id FROM person p WHERE lower(p.name) = ?", array(strtolower($authorNames[$i])));
					$authorID = $authorIDreq->fetchAssocRow();
					
					//insert the new person into the authoring table
					while ( $row = $resourceIDs->fetchAssocRow()) {	//add autoring entries for each resource associated with the paper
						$resourceID = $row['RESOURCEID'];
						$newAuthor = DBExecute("INSERT INTO authoring (personid,resourceid) VALUES (?, ?)", array($authorID['ID'], $resourceID));
					}
				}
			}*/
			if($alreadyExists == false){
				if($_SESSION["errmsg"] ==null || $_SESSION["errmsg"] == '')
					$_SESSION["successmsg"] .= "The publication was added successfully and you are listed as an author of it." . "<br/>";				
			}
			else if($_SESSION["errmsg"] ==null || $_SESSION["errmsg"] == ''){
				$_SESSION["successmsg"] .= "The publication was already in the system. Now you are added as an author of this publication." . "<br/>"
										. "These fields were same as an existing entry: </br>";
				if($duplicateTitle == true){ $_SESSION["successmsg"] .=  'Title' . '<br>';}
				if($duplicateDOI == true){ $_SESSION["successmsg"] .= 'DOI' . '<br>';}
				if($duplicateISBN == true){ $_SESSION["successmsg"] .= 'ISBN' . '<br>';}					
			}
		}

		else{
			$_SESSION["errmsg"] .= "Problem adding publication. Please try again." . "<br/>";
			echo buildRedirectPath($url);
		}
	}
	
	
	echo buildRedirectPath($url);
} 


/// from person_view:
//action=<?php echo "./person_view.php?id=".$id["ID"]."#maintabs-3"?

?>